import { postJson } from './HttpClient';
import { HOST, TOKEN_KEY, LOGIN_KEY, TYPE_KEY } from './Config';
import { currUser } from '../model/CurrUserModel';

export function hasToken() {
    return getToken() != null;
}

export function getToken() {
    return sessionStorage.getItem(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY);
}

export function removeToken() {
    sessionStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem(LOGIN_KEY);
    localStorage.removeItem(TYPE_KEY);
}

interface ILoginResponse {
    token: string;
    userInfo: {
        login: string;
        superAdmin: boolean;
    };
}

export function login(login: string, password: string, rememberMe = false) {
    return postJson(`${HOST}/auth/login`, { login, password }).then((res: ILoginResponse) => {
        rememberMe ? localStorage.setItem(TOKEN_KEY, res.token) : sessionStorage.setItem(TOKEN_KEY, res.token);
        localStorage.setItem(TYPE_KEY, `${res.userInfo.superAdmin || false}`);
        localStorage.setItem(LOGIN_KEY, res.userInfo.login);

        currUser.superAdmin = res.userInfo.superAdmin;
        currUser.login = res.userInfo.login;
        return res;
    });
}